<script setup>
import * as api from "@/api/v-sys-service/sys-manage/user/index.js";
import { useUserStoreHook } from "@/store/modules/user";
import Consts from "@/const"
import userFormDialog from "./user-form-dialog.vue"
import {downloadFile} from "@/utils/index.js";
/**
 * 组件挂载后
 */
onMounted(() => {
  init()
})

/**
 * 列表数据
 */
const tableData = ref([])

/**
 * loading状态
 */
const loading = ref({
  tableLoading: false,// 列表loading
  formBtnLoading: false,// 保存按钮loading
})

/**
 * 弹窗显隐
 */
const dialog = ref({
  showFormDialog: false, //表单弹窗
})

const rowData = ref({})

/**
 * 计算表格属性
 */
const tableInfo = computed(()=>{
  const tableProps = {
    data: tableData.value,
    loading: loading.value.tableLoading,
    checkConfig: { highlight: true },
    checkboxConfig: { reserve: true },
    treeConfig: {
      childrenField: 'children',
    },
    showSelectCount: false,
    showExportBtn: false,
  }
  return { ...tableProps }
})

/**
 * 分页参数
 */
const pageQuery = reactive({
  page: 1,
  limit: 50,
  total: 0,
  orders: [],
  filters: [],
  condition: {
    key: "",
    status: '',
    orgId: '-1',
  },
})


/**
 * 当前登录用户信息
 */
const userStore = useUserStoreHook()

/**
 * 组件初始化调用函数
 */
const init = () => {
  init_PageQuery()
  init_CacheData()
}
const init_CacheData = () => {

}

/**
 * 分页查询
 */
const init_PageQuery = async () => {
  loading.value.tableLoading = true
  const { code, data } = await api.list(pageQuery)
  if (code === 200) {
    loading.value.tableLoading = false
    tableData.value = data.records
    pageQuery.total = data.total
  }
}
/**
 * 重置密码
 */
const resetPassword = (row) => {
  ElMessageBox.prompt(
      "请输入用户「" + row.username + "」的新密码",
      "重置密码",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /\S/,
        inputErrorMessage: "新密码不能为空",
      }
  )
      .then(({ value }) => {
        api.resetPassword(row.id, { password: value }).then(({code}) => {
          if (code === 200) return ElMessage.success("密码重置成功，新密码是：" + value)
        })
      })
}

/**
 * 下载导入模板
 */
const downloadTemplate = async () => {
  const res = await api.downloadTemplate()
  downloadFile(res)
}

/**
 * 导入
 */
const importExcel = async () => {

}

/**
 * form表单
 */
const showFormDialog = ($event,row) => {
  if (row && row.id) rowData.value = row
  else rowData.value = {}
  dialog.value.showFormDialog = true
}

/**
 * 删除
 */
const showRemoveDialog = ($event,row) => {
  ElMessageBox.confirm('', '确定删除吗',
      {
        closeOnClickModal: false,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '拼命加载中...'
            api.remove(row.id).then(({code})=>{
              instance.confirmButtonLoading = false
              if (code === 200){
                ElMessage({
                  message: '删除成功',
                  type: 'success',
                })
                init_PageQuery()
              }
            })
            done()
          } else {
            done()
          }
        }
      }
  )
}

/**
 * 组件对外提供可访问数据
 */
defineExpose({
  showFormDialog,
  showRemoveDialog,
})

const isRoot = ((row)=>{
  const roleCodes = userStore.user.roles
  return !(!roleCodes.includes(Consts.ROOT_ROLE_CODE) && row.roleCodes.includes(Consts.ROOT_ROLE_CODE))
})


</script>

<template>
  <div class="user-box flex">
    <div class="flex flex-col left">
      <v-query-tree v-model="pageQuery.condition.orgId" @query="init_PageQuery"></v-query-tree>
    </div>
    <div class="flex flex-col right">
      <div class="search flex align-center">
      <label class="label">{{'\u2003'}}关键字{{'\u2003'}}</label>
      <el-input
          v-model="pageQuery.condition.key"
          style="width: 180px;" placeholder="请输入关键字"
          @keyup.enter="init_PageQuery" @clear="init_PageQuery" clearable
      />
      <div class="el-button" style="display: none"></div>
      <el-button type="primary" @click="init_PageQuery">
        <template #icon><i-ep-search /></template>搜索
      </el-button>
      <el-button type="success" @click="showFormDialog">
        <template #icon><i-ep-plus /></template>新增
      </el-button>
      <el-button type="primary" @click="downloadTemplate">
        <template #icon><i-ep-download /></template>下载导入模板
      </el-button>
      <el-button type="primary" @click="importExcel">
        <template #icon><i-ep-upload /></template>导入
      </el-button>
    </div>
      <v-table
          v-model="pageQuery"
          :table-info="tableInfo"
          :column-info="api.columnInfo"
          @query="init_PageQuery"
      >
        <template #status="{row}">
          <el-tag v-if="row.status" type="success">启用</el-tag>
          <el-tag v-else type="info">禁用</el-tag>
        </template>
        <template #operate="{row}">
          <el-button type="primary" v-if="isRoot(row)" :text="true" @click="resetPassword(row)">
            <template #icon><i-ep-refresh-left /></template>重置密码
          </el-button>
          <el-button type="primary" v-if="isRoot(row)" :text="true" @click="showFormDialog($event,row)">
            <template #icon><i-ep-edit /></template>编辑
          </el-button>
          <el-button type="primary" v-if="isRoot(row)" :text="true" @click="showRemoveDialog($event,row)">
            <template #icon><i-ep-delete /></template>删除
          </el-button>
        </template>
      </v-table>
    </div>
    <user-form-dialog v-if="dialog.showFormDialog" @query="init_PageQuery" v-model="dialog.showFormDialog" :row-data="rowData"/>
  </div>
</template>

<style scoped lang="scss">
.user-box {
  padding: 10px;
  .left {

  }
  .right {
    width: calc(100% - 300px);
    .container {
      .el-button {
        padding: 0;
      }
    }
  }
}
</style>
